package org.baitu.zzim.registrar;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.baitu.zzim.config.MyNacosProperties;
import org.baitu.zzim.config.NettyProperties;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.util.Properties;

/**
 * @author zhangkai_a
 * @date 2025/7/3 17:43
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NettyNacosRegistrar {

    private final NettyProperties nettyProperties;
    private final MyNacosProperties nacosProperties;
    private NamingService namingService;

    @EventListener(ApplicationReadyEvent.class)
    public void registerToNacos() {
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", nacosProperties.getServerAddr());

            namingService = NacosFactory.createNamingService(properties);

            Instance instance = new Instance();
            instance.setIp(InetAddress.getLocalHost().getHostAddress());
            instance.setPort(nettyProperties.getPort());
            instance.setHealthy(true);
            instance.setWeight(1.0);

            namingService.registerInstance(nettyProperties.getServiceName(), instance);
            log.info("✅ Netty 服务注册成功：[{}:{}]", instance.getIp(), instance.getPort());

        } catch (Exception e) {
            log.error("❌ 注册 Netty 服务到 Nacos 失败", e);
        }
    }

    @PreDestroy
    public void deregister() {
        try {
            namingService.deregisterInstance(nettyProperties.getServiceName(),
                    InetAddress.getLocalHost().getHostAddress(),
                    nettyProperties.getPort());
            log.info("✅ Netty 服务已注销");
        } catch (Exception e) {
            log.warn("⚠️ 注销失败", e);
        }
    }
}